package com.aifast.common.dict;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aifast.common.cache.util.RedisUtil;
import com.aifast.common.global.Const;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DictBindService implements IDictBindService{

    private final static String configName= "main";

    @Override
    public String getDictDataValue(String type, Object value) {
        if (StrUtil.isBlank(type) || ObjectUtil.isNull(value)) {
            return Const.EMPTY;
        }
        String key = getDictMapKey(type);
        String hget = RedisUtil.hget(key, Convert.toStr(value));
        if (RedisUtil.exists(key) && StrUtil.isNotBlank(hget)) {
            return hget;
        }
        String queryStr = Db.use(configName).queryStr("select name from sys_dict_data where deleted is false and type = ? and value = ?", type, value);
        if(StrUtil.isBlank(queryStr)){
            return Const.EMPTY;
        }
        initDictMap();
        return queryStr;
    }


    private static String getDictMapKey(String type) {
        return StrUtil.join(":", Const.PROJECT_NAME_UC,"dict", "map", type);
    }

    private void initDictMap() {
        List<Record> list = Db.use(configName).findAll("sys_dict_data");
        List<String> collect = list.stream().map(i->i.getStr("type")).distinct().collect(Collectors.toList());
        collect.forEach(type -> {
            Map<String, Object> tmp = new HashMap<>();
            list.stream().forEach(l -> {
                if (StrUtil.equals(type, Convert.toStr(l.get("type")))) {
                    tmp.put(l.getStr("type"), l.getStr("name"));
                }
            });
            setDictMapCache(type, tmp);
        });
    }

    private static void setDictMapCache(String type, Map<String, Object> map) {
        String key = getDictMapKey(type);
        RedisUtil.hset(key, map);
    }
}
